const express = require(`express`)
const router = express.Router()
const multer = require('multer')
const adveArtisement = require('../model/Advertisement')
const fs = require('fs')

const storage = multer.diskStorage({
  destination: './public/advertisements',

  filename: function (req, file, cb) {
    console.log(file)
    let extname = file.mimetype.split('/')[1]
    let imgname =
      Date.now() +
      parseInt(Math.random() * 999) +
      parseInt(Math.random() * 2222)
    let keepname = imgname + '广告图片' + '.' + extname
    cb(null, keepname)
  },
})

const upload = multer({
  storage,
})
router.post('/api/v1/uploadimg', upload.single('file'), async (req, res) => {
  console.log(req.body.datas)
  console.log('bodyssssss')
  const datas = JSON.parse(req.body.datas)
  datas.Adimg = req.file.filename
  adveArtisement.create(datas, function (err, doc) {
    console.log('doc', doc)
    if (err) return next(err)
    res.jsonp({
      code: 200,
      data: doc,
    })
  })
})

// 删除请求
router.post('/api/v1/deleteadimg', async (req, res) => {
  console.log(req.body)
  adveArtisement.remove({ _id: req.body._id }, function (err, doc) {
    if (err) {
      res.json({
        code: 400,
        message: 'err',
      })
    } else {
      const filepath = './public/advertisements/' + req.body.fileName
      fs.unlink(filepath, function (err) {
        console.log(err)
        console.log('err==')
        res.json({
          code: 200,
          message: '删除成功',
        })
      })
    }
  })
})
module.exports = router
